#include "ProtobufPkg.h"



ProtobufPkg::ProtobufPkg()
{
	len = 0;
	for (int i = 0; i < PROTOBUFPKG_BUFFER_SIZE; i++) {
		buffer[i] = 0;
	}
}



bool ProtobufPkg::Serializ(void* protoObj, const pb_field_t fields[])
{
	//序列化
		//创建流
	pb_ostream_t stream;
	memset(buffer, 0, sizeof(buffer));
	stream = pb_ostream_from_buffer(buffer, sizeof(buffer));

	//encode
	bool status = pb_encode(&stream, fields, protoObj);
	this->len = stream.bytes_written;		//重点，这里记录了数据的长度		
	return status;
}



bool ProtobufPkg::DeSerializ(void* protoObj, const pb_field_t fields[])
{
	pb_istream_t stream;
	//反序列化
	stream = pb_istream_from_buffer(buffer, len);			//需要传入数据长度
	return pb_decode(&stream, fields, protoObj);		//需要传入fields		
}



void ProtobufPkg::SetBuffer(unsigned char* buf, int len)
{
	this->len = len;
	for (int i = 0; i < len; i++) {
		buffer[i] = buf[i];
	}
}



unsigned char* ProtobufPkg::GetBufferPtr()
{
	return this->buffer;
}



int ProtobufPkg::GetLen()
{
	return len;
}


